<?php
declare (strict_types=1);

namespace app\model\admin;

use app\common\model\BaseModel;
use \libs\Log;

class AvatarFrame extends BaseModel
{
    protected $pk = 'id';

    protected function initialize()
    {
        parent::initialize();
    }
    
    /**
     * 获得列表
     * @param bool $where
     * @param string $fields
     * @param string|null $order
     * @param int $page
     * @param int $pageSize
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($where = true, $fields = '*', $order = null, $page = 1, $pageSize = 20)
    {
        $data = [
            'count' => 0,
            'list' => []
        ];
        $count = $this->where($where)->count();
        if (empty($count)) {
            return $this->returnRight($data);
        }
        $order = is_null($order) ? $this->pk . ' desc' : $order;
        $list = $this->where($where)
            ->field($fields)
            ->order($order)
            ->page($page, $pageSize)
            ->select();
        $data['count'] = $count;
        $data['list'] = $list;
        return $this->returnRight($data);
    }

    public function getOne($data, $fields = '*')
    {
        $info = self::where($this->pk, $data['id'])->field($fields)->find();
        return $info;
    }

    /**
     * 添加
     * @param array $data
     * @return array
     */
    public function add(array $data)
    {
        Log::info('add in parameter', $data);

        // 6.0自动过滤非数据表字段
        self::create($data);
        return $this->returnSucc('调用成功');
    }

    /**
     * 更新
     * @param array $data
     * @return array
     */
    public function edit(array $data, $field)
    {
        $where['id'] = $data['id'];
        $fieldArr = explode(',', $field);
        $this->allowField($fieldArr)
            ->update($data, $where);
        return $this->returnSucc('编辑成功');
    }


    /**
     * 状态更新：启用，禁用，软删除
     * @param array $data
     * @param int $status
     * @return array
     */
    public function changeStatus(array $data, int $status)
    {
        $where['id'] = $data['id'];
        $data['status'] = $status;
        $res = self::update($data, $where);
        if ($res) {
            return $this->returnSucc();
        } else {
            return $this->returnError(1);
        }
    }

    /**
     * @param $data
     * @return array
     * 删除
     */
    public function del($data)
    {
        $res = self::update(['delete_time' => time()], ['id' => $data['id']]);
        if ($res) {
            return $this->returnSucc();
        } else {
            return $this->returnError(1);
        }
    }
}
